package com.xyc.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.xyc.gulimall.order.config.AlipayTemplate;
import com.xyc.gulimall.order.service.OrderService;
import com.xyc.gulimall.order.vo.PayAsyncVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static java.nio.charset.StandardCharsets.ISO_8859_1;

@Slf4j
@RestController
public class OrderPayedListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private HttpServletRequest request;

    /**
     * 处理支付宝支付后的异步通知
     *
     * @param vo
     * @return success
     */
    @PostMapping("/payed/notify")
    public String handleAlipayed(PayAsyncVo vo) throws AlipayApiException, ParseException {
        Map<String, String[]> parameterMap = request.getParameterMap();
        //只要收到了支付宝给我们的异步通知，并且返回success后，支付宝就不会再给我们发送通知了4m，10m，20m...

        // TODO 验签
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes(ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名

        if (signVerified) {
            //验签成功
            log.info("签名验证成功...");
            return orderService.handlePayResult(vo);
        } else {
            //验签失败
            log.error("签名验证失败...");
            return orderService.handlePayResult(vo);
//            return "error";
        }
    }

}
